package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author wsj
 * @since 2022-03-11
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult login(LoginDto dto) {
        //判空
        if (dto==null|| StringUtils.isEmpty(dto.getPassword())&&StringUtils.isEmpty(dto.getPhone())&&StringUtils.isEmpty(dto.getEquipmentId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //如果是手机号密码登录
        if (!StringUtils.isEmpty(dto.getPhone())&&!StringUtils.isEmpty(dto.getPassword())) {
            //验证手机号是否存在
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone,dto.getPhone());
            ApUser one = getOne(queryWrapper);
            if (one==null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //手机号存在，验证密码是否正确
            String md5Pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());
            if (!md5Pwd.equals(one.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //密码正确，制作token
            Map<String, Object> claimMap = new HashMap<>();
            claimMap.put("userId",one.getId());
            String token = AppJwtUtil.getToken(claimMap);
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //脱敏处理
            one.setPassword(null);
            one.setPhone(null);
            one.setSalt(null);
            map.put("user", one);
            //将信息保存到redis中，实现多端无法同时登录功能
            redisTemplate.opsForValue().set(one.getId().toString(),token);
            //返回
            return ResponseResult.okResult(map);
        }
        //如果是游客登录，使用id为0登录
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            Map<String, Object> claimMap = new HashMap<>();
            claimMap.put("userId",0);
            String token = AppJwtUtil.getToken(claimMap);
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //返回响应
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private IApUserFollowService followService;
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //关注用户
        //从线程中获取id
        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //创建对象
        ApUserFollow follow = new ApUserFollow();
        follow.setUserId(user.getId());
        ApUser apUser = getById(user.getId());
        follow.setUserName(apUser.getName());
        //调用文章服务获取作者
        ResponseResult<ApAuthor> result = articleFeign.findById(dto.getAuthorId());
        ApAuthor apAuthor=null;
        if (result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
             apAuthor = result.getData();
        }
        if (apAuthor!=null) {
            follow.setFollowId(apAuthor.getUserId());
            follow.setFollowName(apAuthor.getName());
        }
        follow.setLevel(0);
        follow.setCreatedTime(new Date());
        if (dto.getOperation()==0) {
            //关注，则保存
            followService.save(follow);
        }else {
            //取消关注，则删除
            LambdaQueryWrapper<ApUserFollow> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUserFollow::getFollowId,apAuthor.getUserId());
            wrapper.eq(ApUserFollow::getUserId,user.getId());
            followService.remove(wrapper);
        }
        //发送消息同步行为微服务
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        followBehaviorDto.setUserId(user.getId());
        followBehaviorDto.setFollowId(apAuthor.getUserId());
        followBehaviorDto.setOperation(dto.getOperation());
        kafkaTemplate.send(followBehaviorTopic, JSON.toJSONString(followBehaviorDto));
        return ResponseResult.okResult();
    }
    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
}
